import { defineStore } from 'pinia'
import request from '@/utils/request'

interface Project {
  id: number
  title: string
  description: string
  status: string
  ownerId: number
  createdAt: string
  updatedAt: string
}

interface ProjectState {
  projects: Project[]
  currentProject: Project | null
  loading: boolean
}

export const useProjectStore = defineStore('project', {
  state: (): ProjectState => ({
    projects: [],
    currentProject: null,
    loading: false
  }),

  getters: {
    getProjectById: (state) => (id: number) => {
      return state.projects.find(p => p.id === id)
    },
    getProjectsByStatus: (state) => (status: string) => {
      return state.projects.filter(p => p.status === status)
    }
  },

  actions: {
    async fetchProjects() {
      this.loading = true
      try {
        const response = await request<Project[]>({
          url: '/api/projects',
          method: 'GET'
        })
        this.projects = response.data
      } catch (error) {
        console.error('获取项目列表失败:', error)
      } finally {
        this.loading = false
      }
    },

    async fetchProjectById(id: number) {
      this.loading = true
      try {
        const response = await request<Project>({
          url: `/api/projects/${id}`,
          method: 'GET'
        })
        this.currentProject = response.data
      } catch (error) {
        console.error('获取项目详情失败:', error)
      } finally {
        this.loading = false
      }
    },

    async createProject(project: Omit<Project, 'id' | 'createdAt' | 'updatedAt'>) {
      try {
        const response = await request<Project>({
          url: '/api/projects',
          method: 'POST',
          data: project
        })
        this.projects.push(response.data)
        return response.data
      } catch (error) {
        console.error('创建项目失败:', error)
        throw error
      }
    },

    async updateProject(id: number, project: Partial<Project>) {
      try {
        const response = await request<Project>({
          url: `/api/projects/${id}`,
          method: 'PUT',
          data: project
        })
        const index = this.projects.findIndex(p => p.id === id)
        if (index !== -1) {
          this.projects[index] = response.data
        }
        if (this.currentProject?.id === id) {
          this.currentProject = response.data
        }
        return response.data
      } catch (error) {
        console.error('更新项目失败:', error)
        throw error
      }
    },

    async deleteProject(id: number) {
      try {
        await request({
          url: `/api/projects/${id}`,
          method: 'DELETE'
        })
        this.projects = this.projects.filter(p => p.id !== id)
        if (this.currentProject?.id === id) {
          this.currentProject = null
        }
      } catch (error) {
        console.error('删除项目失败:', error)
        throw error
      }
    }
  }
})